package com.clothing.controller.app;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.clothing.bean.LeaveMessageJson;
import com.clothing.controller.BaseController;
import com.clothing.entity.LeaveMessage;
import com.clothing.entity.LeaveMessageReply;
import com.clothing.entity.User;
import com.clothing.service.LeaveMessageReplyService;
import com.clothing.service.LeaveMessageService;
import com.clothing.service.UserService;
import com.clothing.utils.AjaxMsg;
import com.clothing.utils.Utils;
import com.clothing.utils.page.Page;
import com.clothing.utils.page.Pageable;

/**
 * @ClassName: LeaveMessageController 
 * @Description: TODO(留言) 
 * @author Charles 
 * @date 2017年10月18日 下午3:37:17 
 * @version 1.0
 */
@RequestMapping("/app/leaveMessage")
@Controller("appLeaveMessageController")
public class LeaveMessageController extends BaseController
{
    @Autowired
    private UserService userService;

    @Autowired
    private LeaveMessageService leaveMessageService;

    @Autowired
    private LeaveMessageReplyService leaveMessageReplyService;
    
    /**
     * @Title: submit 
     * @Description: TODO(留言) 
     * @param @param userId
     * @param @param leaveMessageId
     * @param @param content
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    public String submit(Long userId, String content)
    {
        if (Utils.isEmpty(content))
        {
            return getParameterErrorMsg();
        }
        
        User user = userService.find(userId);
        
        if (null == user)
        {
            return getParameterErrorMsg();
        }
        
        User current = userService.getCurrent();
        
        if (current.getId().equals(userId))
        {
            return AjaxMsg.failed("不能给自己留言");
        }

        LeaveMessage leaveMessage = leaveMessageService.findOne(userId, current.getId());
        boolean isNew = false;
        
        if (null == leaveMessage)
        {
            leaveMessage = new LeaveMessage();
            
            if (current.getId() > user.getId())
            {
                leaveMessage.setSmallUser(user);
                leaveMessage.setBigUser(current);
            }
            else
            {
                leaveMessage.setSmallUser(current);
                leaveMessage.setBigUser(user);
            }
            
            isNew = true;
        }   
        
        leaveMessageReplyService.sendMessage(leaveMessage, isNew, userId, content);
        
        return AjaxMsg.success("留言成功");
    }

    /**
     * @Title: list 
     * @Description: TODO(留言列表) 
     * @param @param pageable
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/getList.json", method = RequestMethod.GET)
    @ResponseBody
    public String list(Pageable pageable)
    {
        Long currentId = userService.getCurrentId();
        Page<LeaveMessage> page = leaveMessageService.findPageByUser(currentId, pageable);
        JSONArray ja = null;

        if (page.getTotal() > 0)
        {
            ja = new JSONArray();

            for (LeaveMessage leaveMessage : page.getContent())
            {
                User smallUser = leaveMessage.getSmallUser();
                User bigUser = leaveMessage.getBigUser();
                User user = null;
                LeaveMessageJson json = new LeaveMessageJson();
                
                if (smallUser.getId().equals(currentId))
                {
                    user = bigUser;
                    json.setUnreadQuantity(leaveMessage.getSmallUnreadQuantity());
                }
                else
                {
                    user = smallUser;
                    json.setUnreadQuantity(leaveMessage.getBigUnreadQuantity());
                }
                
                json.setLeaveMessageId(leaveMessage.getId());
                json.setSendDate(leaveMessage.getModifyDate());
                json.setLastMessage(leaveMessage.getLastMessage());
                json.setUserId(user.getId());
                json.setNickName(user.getNickname());
                json.setHeadImgUrl(user.getHeadImgUrl());
                ja.add(json);
            }
        }

        return new AjaxMsg(true, page.getTotal(), ja).toString();
    }
    
    /**
     * @Title: detail 
     * @Description: TODO(留言详情) 
     * @param @param userId
     * @param @param pageable
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/getDetail.json", method = RequestMethod.GET)
    @ResponseBody
    public String detail(Long userId, Pageable pageable)
    {
        if (null == userId)
        {
            return getParameterErrorMsg();
        }
        
        Long currentId = userService.getCurrentId();
        LeaveMessage leaveMessage = leaveMessageService.findOne(userId, currentId);
        JSONArray ja = new JSONArray();
        
        if (null == leaveMessage)
        {
            return new AjaxMsg(true, ja).toString();
        }
        
        Page<LeaveMessageReply> page = leaveMessageReplyService.findLeaveMessageDetail(leaveMessage.getId(), pageable);
        
        if (page.getTotal() > 0)
        {
            for (LeaveMessageReply reply : page.getContent())
            {
                User user = reply.getSender();
                LeaveMessageJson json = new LeaveMessageJson();
                json.setMsgId(reply.getId());
                json.setUserId(user.getId());
                json.setNickName(user.getNickname());
                json.setHeadImgUrl(user.getHeadImgUrl());
                json.setContent(reply.getContent());
                json.setIsMe(user.getId().equals(currentId));
                ja.add(json);
                
                if (!reply.getIsRead()) 
                {
                    reply.setIsRead(Boolean.TRUE);
                    leaveMessageReplyService.update(reply);
                }
            }
        }
        
        if (currentId.equals(leaveMessage.getSmallUser().getId()))
        {
            leaveMessage.setSmallUnreadQuantity(0);
        }
        else
        {
            leaveMessage.setBigUnreadQuantity(0);
        }
        
        leaveMessageService.update(leaveMessage);
        
        return new AjaxMsg(true, page.getTotal(), ja).toString();
    }
    
    /**
     * @Title: unreadDetail 
     * @Description: TODO(获取未读留言列表) 
     * @param @param userId
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/getUnreadDetail.json", method = RequestMethod.GET)
    @ResponseBody
    public String unreadDetail(Long userId)
    {
        if (null == userId)
        {
            return getParameterErrorMsg();
        }
        
        Long currentId = userService.getCurrentId();
        LeaveMessage leaveMessage = leaveMessageService.findOne(userId, currentId);
        
        if (null == leaveMessage)
        {
            return getParameterErrorMsg();
        }
        
        List<LeaveMessageReply> replies = leaveMessageReplyService.findUnreadLeaveMessageDetail(leaveMessage.getId());
        JSONArray ja = null;
        
        if (!Utils.isEmpty(replies))
        {
            ja = new JSONArray();
            
            for (LeaveMessageReply reply : replies)
            {
                User user = reply.getSender();
                LeaveMessageJson json = new LeaveMessageJson();
                json.setMsgId(reply.getId());
                json.setUserId(user.getId());
                json.setNickName(user.getNickname());
                json.setHeadImgUrl(user.getHeadImgUrl());
                json.setContent(reply.getContent());
                json.setIsMe(user.getId().equals(currentId));
                ja.add(json);
                reply.setIsRead(Boolean.TRUE);
                leaveMessageReplyService.update(reply);
            }
        }
        
        if (currentId.equals(leaveMessage.getSmallUser().getId()))
        {
            leaveMessage.setSmallUnreadQuantity(0);
        }
        else
        {
            leaveMessage.setBigUnreadQuantity(0);
        }
        
        leaveMessageService.update(leaveMessage);
        
        return new AjaxMsg(true, ja).toString();
    }
    
    /**
     * @Title: newMessage 
     * @Description: TODO(获取最新消息) 
     * @param @param id
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/getNewMessage.json", method = RequestMethod.GET)
    @ResponseBody
    public String newMessage(Long userId, Long lastMessageId)
    {
        if (null == userId)
        {
            return getParameterErrorMsg();
        }
        
        Long currentId = userService.getCurrentId();
        LeaveMessage leaveMessage = leaveMessageService.findOne(userId, currentId);
        JSONArray ja = null;
        
        if (null == leaveMessage)
        {
            return new AjaxMsg(true, ja).toString();
        }
        
        List<LeaveMessageReply> replies = leaveMessageReplyService.findNewMessage(leaveMessage.getId(), lastMessageId);
        
        if (!Utils.isEmpty(replies))
        {
            ja = new JSONArray();
            
            for (LeaveMessageReply reply : replies)
            {
                User user = reply.getSender();
                LeaveMessageJson json = new LeaveMessageJson();
                json.setMsgId(reply.getId());
                json.setUserId(user.getId());
                json.setNickName(user.getNickname());
                json.setHeadImgUrl(user.getHeadImgUrl());
                json.setContent(reply.getContent());
                json.setIsMe(user.getId().equals(currentId));
                ja.add(json);
                reply.setIsRead(Boolean.TRUE);
                leaveMessageReplyService.update(reply);
            }
        }
        
        if (currentId.equals(leaveMessage.getSmallUser().getId()))
        {
            leaveMessage.setSmallUnreadQuantity(0);
        }
        else
        {
            leaveMessage.setBigUnreadQuantity(0);
        }
        
        leaveMessageService.update(leaveMessage);
        
        return new AjaxMsg(true, ja).toString();
    }
}
